import pickle

from sklearn import svm
import scipy.io as scio
import numpy as np

def Accuracy(model, xTest, yTest):
    errCnt = 0
    res = model.predict(xTest)
    for i in range(0, len(res)):
        if(res[i] != yTest[i]):
            errCnt = errCnt + 1
    return 1 - errCnt/len(res)
#边训练边测试，结束后保存
def TrainAndSave(model, x , y, xTest, yTest):

    for i in range(0, len(xTest)):
        x = np.row_stack((x, xTest[i]))
        y = np.row_stack((y, yTest[i]))
        '''
        print("x:")
        print(x)
        print("y:")
        print(y)
        '''
        model.fit(x, y)
        res = model.predict(xTest)
        errCnt = 0
        for j in range(0, len(res)):
            if(res[j] != yTest[j]):
                errCnt = errCnt + 1
        print("第", i, "次训练后，识别的准确率为：")
        print(1-errCnt/len(res))
    s = pickle.dumps(model)
    f = open('svm.model', "wb+")
    f.write(s)
    f.close()
    print("模型保存完成\n")


spamTrain = scio.loadmat('spamTrain.mat')
x = spamTrain['X']
y = spamTrain['y']
model = svm.SVC(C=0.1, kernel='linear')
model.fit(x, y)

spamTest = scio.loadmat('spamTest.mat')
xTest = spamTest['Xtest']
yTest = spamTest['ytest']
print("x:")
print(x)
print("y:")
print(y)
print("xTest:")
print(xTest)
print("yTest:")
print(yTest)
print(Accuracy(model, xTest, yTest))
TrainAndSave(model, x, y, xTest, yTest)






#emailSample1 = open("emailSample1.txt").read()
#print(emailSample1)